package com.futuremind.recyclerviewfastscroll;

import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;

public class ListContainerScrolledListener implements ListContainer.ScrolledListener {
    private final FastScroller scrolled;
    private List<ScrolledListener> listeners = new ArrayList<>();
    private int oldScrollState = Component.SCROLL_IDLE_STAGE;

    public List<ScrolledListener> getListeners() {
        return listeners;
    }

    /**
     * 实例化 ListContainerScrolledListener
     *
     * @param scrolled FastScroller
     */
    public ListContainerScrolledListener(FastScroller scrolled) {
        this.scrolled = scrolled;
    }

    /**
     * 添加监听
     *
     * @param listener 监听
     */
    public void addScrolledListener(ScrolledListener listener) {
        listeners.add(listener);
    }

    @Override
    public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
        ListContainer listContainer = (ListContainer) component;
        if (scrolled.shouldUpdateHandlePosition()) {
            updateHandlePosition(listContainer);
        }
    }

    @Override
    public void scrolledStageUpdate(Component component, int newScrollState) {
        if (newScrollState == Component.SCROLL_IDLE_STAGE && oldScrollState != Component.SCROLL_IDLE_STAGE) {
            scrolled.getViewProvider().onScrollFinished();
        } else if (newScrollState != Component.SCROLL_IDLE_STAGE && oldScrollState == Component.SCROLL_IDLE_STAGE) {
            scrolled.getViewProvider().onScrollStarted();
        }
        oldScrollState = newScrollState;
    }

    void updateHandlePosition(ListContainer lc) {
        float relativePos;
        if (lc.getOrientation() == Component.VERTICAL) {
            int offset = lc.getScrollValue(Component.AXIS_Y);
            int extent = lc.getHeight();
            int range = scrolled.getTotalScrollH();
            relativePos = offset / (float) (range - extent);
        } else {
            int offset = lc.getScrollValue(Component.AXIS_X);
            int extent = lc.getWidth();
            int range = scrolled.getTotalScrollW();
            relativePos = offset / (float) (range - extent);
        }
        scrolled.setScrolledPosition(relativePos);
        notifyListeners(relativePos);

    }

    /**
     * 通知 ScrolledListener更新
     *
     * @param relativePos item 位置
     */
    public void notifyListeners(float relativePos) {
        for (ScrolledListener listener : listeners) listener.onScroll(relativePos);
    }

    public interface ScrolledListener {
        /**
         * 滚动位置
         *
         * @param relativePos item 位置
         */
        void onScroll(float relativePos);
    }
}
